<template>
  <a-spin :spinning="tableLoading">
    <a-card class="app">



      <a-row justify="space-between">
        <a-col :span="12">
          <a-space :size="20">
            <h2 style="display: inline">
              <CaretLeftFilled @click="back()" />
            </h2>
            <h2 style="display: inline">课程</h2>
            <h3 style="display: inline">{{ data.form.docEntry }}</h3>
            <a-space :size="12">
              <a-button shape="circle">
                {{ data.form.docStatus }}
              </a-button>
              <a-button shape="circle">
                <LockOutlined />
              </a-button>
              <a-button shape="circle"
                :type="data.form.approved ? 'primary' : 'default'">
                <CheckOutlined />
              </a-button>
              <a-button shape="circle">
                <FlagOutlined />
              </a-button>

              <a-button shape="circle"
                @click="print()">

                <PrinterOutlined />
              </a-button>


            </a-space>
          </a-space>
        </a-col>
        <a-col :span="12">
          <a-row justify="end">
            <a-space :size="6"
              v-if="!data.form.edit">
              <a-button size="small"
                type="primary"
                @click="edit()"
                v-if="!(data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved)">
                <FormOutlined />
                编辑
              </a-button>
              <a-button size="small"
                type="primary"
                danger
                @click="del()"
                v-if="data.form.docStatus === 'O' && !data.form.approved">
                <DeleteOutlined />删除
              </a-button>
              <a-dropdown>
                <a-button size="small"
                  v-if="!(data.form.docStatus === 'L')">更多操作
                  <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu @click="more">
                    <a-menu-item key="a"
                      v-if="data.form.docStatus !== 'C'">完工</a-menu-item>
                    <a-menu-item key="b"
                      v-if="data.form.docStatus === 'C'">取消完工</a-menu-item>
                    <a-menu-item key="c"
                      v-if="!data.form.approved">发起审核</a-menu-item>
                    <a-menu-item key="d"
                      v-if="data.form.approved">取消审核</a-menu-item>
                    <a-menu-item key="e"
                      v-if="!data.form.playStatus">规划</a-menu-item>
                    <a-menu-item key="f"
                      v-if="data.form.playStatus">取消规划</a-menu-item>
                    <a-menu-item key="g"
                      v-if="!data.form.issuStatus">下达</a-menu-item>
                    <a-menu-item key="h"
                      v-if="data.form.issuStatus">取消下达</a-menu-item>
                    <a-menu-item key="i">领料通知单</a-menu-item>
                    <a-menu-item key="j">产品送检单</a-menu-item>


                  </a-menu>
                </template>
              </a-dropdown>
              <a-button size="small"
                @click="refresh">
                <RetweetOutlined />
                刷新
              </a-button>
            </a-space>
          </a-row>
        </a-col>
      </a-row>



      <br />





      <a-form ref="formRef"
        :model="data.form"
        :rules="data.rules"
        :label-col="{ span: 6 }">
        <a-row class="smart-query-form-row">
          <a-col :span="8">
            <a-form-item label="部门"
              name="deptId">
              <DepartmentTreeSelect v-if="data.form.edit"
                :init="false"
                v-model:value="data.form.deptId"
                @update:value="change" />
              <span v-else>{{ data.form.deptName }}</span>
            </a-form-item>
            <a-form-item label="生产订单类型"
              name="type">
              <a-select v-if="data.form.edit"
                v-model:value="data.form.type">
                <a-select-option key="A">单体生产指令</a-select-option>
                <a-select-option key="B">混晶生产指令</a-select-option>
                <a-select-option key="C">包装生产指令</a-select-option>
              </a-select>
              <span v-else>

                <span v-if="data.form.type === 'A'">单体生产指令</span>
                <span v-if="data.form.type === 'B'">混晶生产指令</span>
                <span v-if="data.form.type === 'C'">包装生产指令</span>



              </span>
            </a-form-item>
            <a-form-item label="产品编码"
              name="itemId">
              <span>{{ data.form.itemId }}</span>
            </a-form-item>
            <a-form-item label="产品名称"
              name="itemName">
              <span>{{ data.form.itemName }}</span>
            </a-form-item>
            <a-form-item label="数量"
              name="qty">
              <span>{{ excute(data.form.qty) }}</span>
            </a-form-item>
            <a-form-item label="规格"
              name="specs">
              <span>{{ data.form.specs }}</span>
            </a-form-item>
            <a-form-item label="单位"
              name="unit">
              <span>{{ data.form.unit }}</span>
            </a-form-item>
          </a-col>

          <a-col :span="8">
            <a-form-item label="合同号"
              name="connum">
              <span v-text="data.form.connum"></span>
            </a-form-item>
            <a-form-item label="规划状态"
              name="playStatus">
              <span>{{ data.form.playStatus ? '已规划' : '未规划' }}</span>
            </a-form-item>
            <a-form-item label="规划日期"
              name="playDateTime">
              <span>{{ data.form.playDateTime }}</span>
            </a-form-item>
            <a-form-item label="下达状态"
              name="issuStatus">
              <span>{{ data.form.issuStatus ? '已下达' : '未下达' }}</span>
            </a-form-item>
            <a-form-item label="下达日期"
              name="issuDateTime">
              <span>{{ data.form.issuDateTime }}</span>
            </a-form-item>

            <a-form-item label="备注">
              <a-textarea v-if="data.form.edit"
                v-model:value="data.form.remark"
                :rows="2" />
              <span v-else>{{ data.form.remark }}</span>
            </a-form-item>
            <a-form-item label="制单">
              <span>{{ data.form.createBy + '&nbsp;&nbsp;' + data.form.createTime }}</span>
            </a-form-item>
            <a-form-item label="修改">
              <span>{{ data.form.updateBy + '&nbsp;&nbsp;' + data.form.updateTime }}</span>
            </a-form-item>

          </a-col>

        </a-row>
      </a-form>
      <a-row>
        <a-tabs v-model:activeKey="data.activeKey"
          style="width: 100%">
          <a-tab-pane key="1"
            tab="物料清单">
            <a-button @click="lineaAdd()"
              type="link"
              v-if="!data.form.approved && data.form.docStatus === 'O'">
              <template #icon>
                <ExportOutlined />
              </template>
              新增
            </a-button>
            <a-table row-key="lineNum"
              :scroll="{ y: 650, x: 1500 }"
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                showQuickJumper: true,
              }"
              :columns="columnsa"
              :data-source="data.form.lista"
              stripe
              defaultExpandAllRows>
              <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'qty'">
                  <span>{{ excute(text) }}</span>
                </template>

                <template v-if="column.dataIndex === 'kitting'">
                  <span>{{ text ? '齐套' : '非齐套' }}</span>
                </template>

                <template v-if="column.dataIndex === 'action'">
                  <a-button-group>
                    <a-button size="small" type="link"

                      @click="lineaEdit(record)">
                      <FormOutlined />
                    </a-button>

                    <a-button size="small" @click="lineaDel(record)"
                      type="link"
                      danger>
                      <DeleteOutlined />
                    </a-button>
                  </a-button-group>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
          <a-tab-pane key="2"
            tab="工艺路线">
            <a-row class="smart-table-btn-block">
              <div class="smart-table-operate-block">
                <a-button @click="linebAdd"
                  type="link"
                  v-if="!data.form.approved && data.form.docStatus === 'O'">
                  <ExportOutlined />
                  新增
                </a-button>
              </div>
            </a-row>
            <a-table row-key="lineNum"
              :scroll="{ y: 650, x: 600 }"
              defaultExpandAllRows
              :pagination="{
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '30', '40'],
                defaultPageSize: 20,
                showQuickJumper: true,
              }"
              :columns="columnsa"
              :data-source="data.form.listb"
              summary-fixed
              stripe>
              <template #bodyCell="{ text, record, column }">
                <template v-if="record.edit && column.dataIndex === 'nowDate'">
                  <a-date-picker v-model:value="record.nowDate"
                    valueFormat="YYYY-MM-DD" />
                </template>

                <template v-if="column.dataIndex === 'workDay'">
                  {{ text ? '是' : '否' }}
                </template>

                <template v-if="column.dataIndex === 'action'">
                  <a-button-group>
                    <a-button type="link"
                      @click="showForm(record)">
                      <FormOutlined />
                    </a-button>
                    <a-button
                      :disabled="data.form.docStatus === 'L' || data.form.docStatus === 'C' || data.form.approved"
                      @click="linebDel(record)"
                      type="link"
                      danger>
                      <template #icon>
                        <DeleteOutlined />
                      </template>
                    </a-button>
                  </a-button-group>
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-row>


      <a-row style="margin-top: 20px">
        <a-col :span="24">
          <a-button-group v-if="data.form.edit">
            <a-button @click="save()" type="primary" >保存</a-button>
            <a-button @click="refresh" > 取消</a-button>

          </a-button-group>
        </a-col>
      </a-row>





    </a-card>


  </a-spin>

  <!--  <Approvord v-if="data.visible.approvord" :approvedData="data.approvedData" :visible="data.visible.approvord" :on-close="onclose"></Approvord>-->

  <MmordForm ref="mmordFormRef"
    @reloadList="queryData"></MmordForm>
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { mmordApi, mmordaApi, mmordbApi } from '/src/api/business/erp/mmord-api';
import { useRouter, useRoute } from 'vue-router';
import DepartmentTreeSelect from '/src/components/system/department-tree-select/index.vue';
import Approvord from '/src/components/business/erp/approved.vue';
import MmordForm from '/src/views/business/erp/mmo/component/mmord-form.vue';

import { approvordApi } from '/src/api/business/erp/approvord-api.js';
import { excute } from '../../../../utils/numformat-util.js';
// ---------------------------- 表格列 ----------------------------
const route = useRoute();
const router = useRouter();
const data = reactive({
  form: {
    id: null,
    objId: '',
    absId: '',
    approved: false,
    docStatus: 'O',
    edit: false,
    lista: [],
    listb: [],
    listc: [],
    listd: [],
  },
  radioGroup: null,
  rules: {
    type: [{ required: true, message: '' }],
    deptId: [{ required: true, message: '' }],
    itemName: [{ required: true, message: '' }],
  },
  model: {
    absId: '',
  },
  editableData: {
    nowDate: null,
  },
  activeKey: '1',
  visible: {
    mac: false,
    user: false,
    approvord: false,
    nmmord: false,
  },
  approvedData: {
    baseEntry: null,
    tabName: null,
  },
  groupActive: '1',
});

const columnsa = ref([
  {
    title: '行号',
    dataIndex: 'lineNum',
    align: 'center',
    width: 100,
  },
  {
    title: '物料编码',
    dataIndex: 'itemId',
    align: 'left',
    width: 100,
  },
  {
    title: '物料名称',
    dataIndex: 'itemName',
    align: 'left',
    width: 100,
  },
  {
    title: '规格',
    dataIndex: 'specs',
    align: 'left',
    width: 160,
    ellipsis: true,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    align: 'center',
    width: 100,
  },
  {
    title: '数量',
    dataIndex: 'qty',
    align: 'right',
    width: 100,
  },

  {
    title: '齐套领料',
    dataIndex: 'kitting',
    align: 'center',
    width: 100,
  },
  {
    title: '领料数量',
    dataIndex: 'mrqQty',
    align: 'right',
    width: 100,
  },

  {
    title: '操作',
    dataIndex: 'action',
    width: 100,
    fixed: 'right',
    align: 'center',
  },
]);

const tableLoading = ref(false);
const formRef = ref(null);

function init() {
  if (route.query.type === 'info') {
    data.form.id = route.query.id;
    queryData();
  } else {
    data.form.edit = true;
  }
}

onMounted(init);

// 查询数据
function queryData() {
  tableLoading.value = true;
  formRef.value.resetFields();
  mmordApi
    .info(data.form.id)
    .then((res) => {
      data.form = res.data;
    })
    .finally(() => {
      tableLoading.value = false;
    });
}

function back() {
  router.push({ path: '/erp/mmord' });
}

function save() {
  formRef.value
    .validate()
    .then(() => {
      tableLoading.value = true;

      if (data.form.id) {
        mmordApi.update(data.form).then((res) => {
          queryData(data.form.id);
          message.success('修改成功！');
        });
      } else {
        mmordApi.add(data.form).then((res) => {
          data.form.id = res.data;
          message.success('保存成功！');
          router.push({ path: '/erp/mmorda', query: { type: 'info', id: res.data } });
          queryData(res.data);
        });
      }
    })
    .catch((err) => {
      message.error('页面校验失败！');
    });
}

function edit() {
  data.form.edit = true;
  data.form.lista.forEach((item) => {
    item.edit = true;
  });
}

function del() {
  Modal.confirm({
    content: `确认删除（${data.form.id}）`,
    onOk() {
      mmordApi.delete(data.form.id).then((res) => {
        message.success('删除成功！');
        router.push({ path: '/erp/mmord' });
      });
    },
    cancelText: '取消',
    onCancel() {
      Modal.destroyAll();
    },
  });
}

// 更多操作
function more({ key }) {
  // 审核处理函数

  if (key === 'a') {
    data.form.docStatus = 'C';
    tableLoading.value = true;
    mmordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'b') {
    data.form.docStatus = 'O';
    tableLoading.value = true;
    mmordApi.update(data.form).then((res) => {
      tableLoading.value = false;
      queryData();
    });
  } else if (key === 'c') {
    approvordApi
      .add({
        id: null,
        approvLineNum: 2,
        approvType: 'A',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'd') {
    approvordApi
      .add({
        id: 0,
        approvLineNum: 2,
        approvType: 'B',
        baseEntry: data.form.id,
        tabName: data.form.objName,
        docStatus: 'O',
        tabId: data.form.objId,
        baseVersion: data.form.version,
      })
      .then((res) => {
        queryData();
      });
  } else if (key === 'e') {
    tableLoading.value = true;
    mmordApi
      .onPlan(data.form.id)
      .catch((err) => {
        message.error(err);
      })
      .finally(() => {
        queryData();
        tableLoading.value = false;
      });
  } else if (key === 'f') {
    tableLoading.value = true;
    mmordApi
      .unOnPlay(data.form.id)
      .catch((error) => {
        message.error(error);
      })
      .finally(() => {
        queryData();
        tableLoading.value = false;
      });
  } else if (key === 'i') {
    router.push({ path: 'mrnorda', query: { type: 'tager', id: data.form.id } });
  } else if (key === 'j') {
    router.push({ path: 'prforda', query: { type: 'tager', id: data.form.id } });
  }
}

function refresh() {
  queryData();
}

function change(item, key) {
  data.form.deptName = key;
}

// 审核------------------------------------------------------------------------------------------------
function approved() {
  data.approvedData.baseEntry = data.form.id;
  data.approvedData.tabName = data.form.objName;
  data.visible.approvord = true;
}

function lineaEdit(item) {
  mmordFormRef.value.show(item);
}

const mmordFormRef = ref(null);

function lineaAdd() {
  mmordFormRef.value.show({
    id: data.form.id,
  });
}

function lineaDel(item) {
  tableLoading.value = true;
  mmordaApi.deleteLine(item).then((res) => {
    tableLoading.value = false;
    queryData();
  });
}

/* -------------------------------------B----------------------------------------------*/

function linebAdd() {
  data.visible.user = true;
}

function linebDel(item) {
  tableLoading.value = true;
  mmordbApi
    .deleteLine(item)
    .then((res) => {
      queryData();
    })
    .finally(() => {
      tableLoading.value = false;
    });
}
</script>
